package com.wuxuan.algorithm_homework.bit;

import org.junit.jupiter.api.Test;

/**
 * 位运算
 */
public class BitDemo {

    /**
     * 按位与运算符(&)
     */
    @Test
    public void testBitwiseAndExample() {
        int result = 5 & 3;
        //0 1 0 1
        //0 0 1 1
        //0 0 0 1
        // 1
        System.out.println(result);
    }

    /**
     * 按位或运算符(|)
     */
    @Test
    public void testBitwiseOrExample() {
        int result = 5 | 3;
        //0 1 0 1
        //0 0 1 1
        //0 1 1 1
        //
        System.out.println(result);
    }

    /**
     * 按位异或运算符(^)
     */
    @Test
    public void testBitwiseXorExample() {
        int result = 5 ^ 3;
        //0 1 0 1
        //0 0 1 1
        //0 1 1 0
        // 6
        System.out.println(result);
    }

    /**
     * 应用场景：交换两个变量的值(不使用临时变量)
     */
    @Test
    public void testSwapExample() {
        int a = 5;
        int b = 3;
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

        System.out.println("a = " + a + ", b = " + b);
    }

    /**
     * 左移运算符(<<)
     */
    @Test
    public void testLeftShiftExample() {
        int result = 5 << 2;
        System.out.println(result);
    }

    /**
     * 右移运算符(>>)
     */
    @Test
    public void testRightShiftExample() {
        int result = 5 >> 1;
        System.out.println(result);
    }

}
